//
//  ListViewController.m
//  We365
//
//  Created by Pham Khuong Duy on 12/14/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ListViewController.h"
#import "Settings.h"
#import "SBJson.h"
#import "Item.h"
#import "BusinessViewController.h"
#import "Utilities.h"
#import "MainViewController.h"

@implementation ListViewController
@synthesize alert;
@synthesize table;
@synthesize allListItem;
@synthesize listItem;
@synthesize category;
@synthesize searchKey;
@synthesize webData;
@synthesize search;
@synthesize conn;

enum requestTypes isGetting;
int selectedIndex;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithCategory:(Category *)c andKey:(NSString *)k
{
    self = [super init];
    allListItem = [[NSMutableArray alloc] init];
    listItem = [[NSMutableArray alloc] init];
    [self setCategory:c];
    [self setSearchKey:k];
    return self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    int count = [self.navigationController.viewControllers count];
    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
        NSLog(@"View will disappear loading...count:");
        NSLog(@"%d",count);
        if (count == 1) {
            NSLog(@"Main View Will Display");
            NSLog(@"goBack function");
            [UIView beginAnimations:@"animation" context:nil];
            [UIView setAnimationDuration:1.0];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
            [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:NO];
            [self.navigationController popViewControllerAnimated:NO];
            [UIView commitAnimations];

        }
        else {
            NSLog(@"Not Found View Main");
        }
    }
    
    search.text = @"";
    [search resignFirstResponder];
    search.showsCancelButton = NO;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    alert = [[UIAlertView alloc] initWithTitle:@"Loading..." message:@" " delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
    progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [alert addSubview:progress];
    [progress startAnimating];
    [progress release];

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:BGSearch]];
    // Search Bar
    // Transperance SearchBar Background
    search.delegate = self;
    [[[search subviews] objectAtIndex:0] removeFromSuperview];
    
    search.tintColor = [UIColor colorWithRed:53.0f/255.0f green:91.0f/255.0f blue:0.0f alpha:1.0f]; 
    
    [self getAllItems];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setAlert:nil];
    [self setTable:nil];
    [self setAllListItem:nil];
    [self setListItem:nil];
    [self setSearch:nil];
    [self setConn:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc 
{
    [alert release];
    [table release];
    [allListItem release];
    [listItem release];
    [category release];
    [searchKey release];
    [webData release];
    [search release];
    [super dealloc];
}

- (void)getAllItems
{
    CLLocation *location = [MainViewController getLocation];
    
    [alert show];   
    
    int radius = [[[Settings getAllSettings] objectForKey:kDistance] intValue];
    NSMutableString *urlString = [NSMutableString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%d&sensor=false&key=AIzaSyDk4EnnRpfhd0knpKCMLffmifq5GzR7kOI", location.coordinate.latitude, location.coordinate.longitude, radius];
    if([searchKey length] != 0)
        [urlString appendString:[NSString stringWithFormat:@"&name=%@", searchKey]];
    if(category != nil)
        [urlString appendString:[NSString stringWithFormat:@"&types=%@", category.SearchKey]];
    
    isGetting = isGettingItems;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    conn = [NSURLConnection connectionWithRequest:request delegate:self];       
}

- (void)getDistances
{
    if([allListItem count] == 0)
    {
        webData = nil;
        conn = nil;
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        return;
    }
    
    CLLocation *location = [MainViewController getLocation];
    
    NSMutableString *urlString = [NSMutableString stringWithFormat:@"https://maps.googleapis.com/maps/api/distancematrix/json?origins=%f,%f&sensor=false&destinations=", location.coordinate.latitude, location.coordinate.longitude];
    for(Item *item in allListItem)    
        [urlString appendString:[NSString stringWithFormat:@"%f,%f|", item.Latitude, item.Longitude]];    
      
    isGetting = isGettingDistances;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];     
    conn = [NSURLConnection connectionWithRequest:request delegate:self];   
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{    
    if(webData == nil)
        webData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    webData = nil;
    conn = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{    
    NSString *responseString = [[[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *root = [responseString JSONValue];
    
    if(isGetting == isGettingItems)
    {
        NSArray *results = [root objectForKey:@"results"];            
        for (int i=0; i<[results count]; i++) {
            NSDictionary *item = [results objectAtIndex:i];
            NSDictionary *geometry = [item objectForKey:@"geometry"];
            NSDictionary *location = [geometry objectForKey:@"location"];
            Item *newItem = [[Item alloc] init];
            newItem.Latitude = [[location objectForKey:@"lat"] floatValue];
            newItem.Longitude = [[location objectForKey:@"lng"] floatValue];
            newItem.Rating = [[item objectForKey:@"rating"] floatValue];
            newItem.ItemID = (NSString *)[item objectForKey:@"id"];
            newItem.ItemName = (NSString *)[item objectForKey:@"name"];
            newItem.Reference = (NSString *)[item objectForKey:@"reference"];
            //newItem.Address = (NSString *)[item objectForKey:@"vicinity"];
            [allListItem addObject:newItem];
            [newItem release];
        }
        [self resetSearch];
        webData = nil;
        conn = nil;
        //[table reloadData];
        [self getDistances];
    } 
    else if(isGetting == isGettingDistances)
    {
        NSArray *rows = [root objectForKey:@"rows"];
        NSDictionary *row = [rows objectAtIndex:0];
        NSArray *elements = [row objectForKey:@"elements"];
        for(int i=0; i<[elements count]; i++)    
        {
            NSDictionary *element = [elements objectAtIndex:i];
            NSDictionary *distance = [element objectForKey:@"distance"];
            
            Item *item = [allListItem objectAtIndex:i];
            item.Distance = [[distance objectForKey:@"value"] floatValue] / 1000;
        }
        [table reloadData];
        webData = nil;
        conn = nil;
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    }        
    else
    {
        Item *item = [listItem objectAtIndex:selectedIndex];
        
        NSDictionary *result = [root objectForKey:@"result"];
        item.Address = (NSString *)[result objectForKey:@"formatted_address"];
        item.Phone = (NSString *)[result objectForKey:@"formatted_phone_number"];
        item.Website = (NSString *)[result objectForKey:@"website"];
        
        webData = nil;
        [alert dismissWithClickedButtonIndex:0 animated:YES];        
        
        BusinessViewController *business = [[BusinessViewController alloc] initWithItem:item];
        [self.navigationController pushViewController:business animated:YES];
        [business release];
    }    
}

- (NSString *)title
{
    if(category == nil)
        return searchKey;
    else
        return category.CategoryName;
}

- (void)resetSearch
{
    listItem = [self.allListItem mutableCopy];    
}

- (void)handleSearch:(NSString *)key
{
    [self resetSearch];
    NSMutableArray *toRemove = [[NSMutableArray alloc] init];
    for (Item *item in listItem) {
        if([item.ItemName rangeOfString:key options:NSCaseInsensitiveSearch].location == NSNotFound)
            [toRemove addObject:item];
    }
    [listItem removeObjectsInArray:toRemove];
    [table reloadData];
    [toRemove release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [listItem count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:identifier];
    UILabel *name = nil;
    UILabel *rating = nil;
    UILabel *distance = nil;
    if(cell == nil)
    {        
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];    
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        name = [[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 250, 25)] autorelease];        
        name.tag = 1;
        name.font = [UIFont boldSystemFontOfSize:20];
        name.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:name]; 
        
        rating = [[[UILabel alloc] initWithFrame:CGRectMake(5, 30, 250, 25)] autorelease];        
        rating.tag = 2;
        rating.font = [UIFont italicSystemFontOfSize:15];
        rating.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:rating]; 
        
        distance = [[[UILabel alloc] initWithFrame:CGRectMake(255, 24, 70, 12)] autorelease];        
        distance.tag = 3;
        distance.font = [UIFont systemFontOfSize:12];
        distance.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:distance];     
    }
    else
    {
        name = (UILabel *)[cell.contentView viewWithTag:1];
        rating = (UILabel *)[cell.contentView viewWithTag:2];
        distance = (UILabel *)[cell.contentView viewWithTag:3];
    }
        
    int row = [indexPath row];
    
    if (row % 2 == 0) {
        //name.textColor = [UIColor whiteColor];
        UIColor *colorEven = [UIColor colorWithRed:0.0f/255.0f green:168.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
        //UIColor *colorOdd = [UIColor colorWithRed:255.0f/255.0f green:90.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
        
        name.textColor = colorEven;
        distance.textColor = colorEven;
        rating.textColor = colorEven;
        
        
        name.shadowColor = [UIColor whiteColor];
        name.shadowOffset = CGSizeMake(0, 0.8f);
        distance.shadowColor = [UIColor whiteColor];
        distance.shadowOffset = CGSizeMake(0, 0.8f);
        rating.shadowColor = [UIColor whiteColor];
        rating.shadowOffset = CGSizeMake(0, 0.8f);
    }
    else
    {
        UIColor *colorOdd = [UIColor colorWithRed:255.0f/255.0f green:90.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
        //UIColor *colorEven = [UIColor colorWithRed:0.0f/255.0f green:168.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
        
        name.textColor = colorOdd;
        distance.textColor = colorOdd;
        rating.textColor = colorOdd;
        

        name.shadowColor = [UIColor yellowColor];
        name.shadowOffset = CGSizeMake(0, 0.8f);
        distance.shadowColor = [UIColor yellowColor];
        distance.shadowOffset = CGSizeMake(0, 0.8f);
        rating.shadowColor = [UIColor yellowColor];
        rating.shadowOffset = CGSizeMake(0, 0.8f);

    }
    
    
    Item *item = [listItem objectAtIndex:row];
    name.text = item.ItemName;
    rating.text = [NSString stringWithFormat:@"Rating: %.2f", item.Rating];
    if(!isGettingItems)
    {
        if([[Settings getAllSettings] objectForKey:kMeasureKind] == kMilesF)
        {
            distance.text =  [NSString stringWithFormat:@"%.1f mi", [Utilities convertKmtoMiles:item.Distance]];
        }
        else
        {
            distance.text = [NSString stringWithFormat:@"%.1f km", item.Distance];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row%2) {
        cell.backgroundColor = [UIColor clearColor];
        
    }
    else {
        // 192-200-214
        cell.backgroundColor = [UIColor colorWithRed:217.0f/255.0f green:228.0f/255.0f blue:249.0f/255.0f alpha:1.0f];
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [alert show]; 
    
    selectedIndex = [indexPath row];
    Item *item = [listItem objectAtIndex:selectedIndex];
    
    NSMutableString *urlString = [NSMutableString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/details/json?reference=%@&sensor=true&key=AIzaSyDk4EnnRpfhd0knpKCMLffmifq5GzR7kOI", item.Reference];
    
    isGetting = isGettingDetail;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];     
    conn = [NSURLConnection connectionWithRequest:request delegate:self];   
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [search resignFirstResponder];
    return indexPath;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(isGetting == isGettingItems || isGetting == isGettingDistances)
        [self.navigationController popViewControllerAnimated:YES];
    conn = nil;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if([searchText length] == 0)
    {
        [self resetSearch];
        [table reloadData];
        return;
    }
    [self handleSearch:searchText];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [search setShowsCancelButton:YES animated:YES];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    search.text = @"";
    [self resetSearch];
    [table reloadData];
    [search resignFirstResponder];
    [search setShowsCancelButton:NO animated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self handleSearch:[searchBar text]];
    [search resignFirstResponder];
    [search setShowsCancelButton:NO animated:YES];
}

@end
